package com.hkunderground.blogger;

import java.io.IOException;

import java.net.URL;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.GoogleService;
import com.google.gdata.client.Query;
import com.google.gdata.data.Feed;
import com.google.gdata.data.Entry;
import com.google.gdata.data.HtmlTextConstruct;
import com.google.gdata.data.TextConstruct;
import com.google.gdata.data.TextContent;
//import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.hkunderground.blogger.helper.ConstantHelper;
import com.hkunderground.blogger.helper.PropertiesHelper;
import com.hkunderground.blogger.helper.UtilHelper;
import com.hkunderground.blogger.obj.Blog;

@SuppressWarnings("serial")
public class HkugBloggerServlet extends HttpServlet 
{
	protected GoogleService myService = null; 
	
	public void init(ServletConfig config) throws ServletException
	{  
		myService= new GoogleService(ConstantHelper.SERVICE_NAME_BLOGGER, ConstantHelper.APPLICATION_NAME_BLOGGER);
/*
		try 
		{
			myService.setUserCredentials(PropertiesHelper.getBlogUser(), PropertiesHelper.getBlogPwd());
		} 
		catch (AuthenticationException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ServletException(e);
		}//try
*/
		super.init(config); //added this line then it worked  
	}//init
	

	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException,ServletException {
		resp.setContentType(ConstantHelper.CONTENT_TYPE_UTF8);
		resp.setCharacterEncoding(ConstantHelper.CHARACTER_ENCODING_UTF8);	    
		doPost(req, resp);
	}//doGet
	

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException,ServletException
	{
		
		String lsPathInfo = req.getPathInfo();
		int liStartIndex = 1;
		

		try 
		{
			Blog[] loBlogArr = null;
			
			if (lsPathInfo == null)
			{
				loBlogArr =  this.getBlogList(liStartIndex);
				
				if (this.isNextFeed(liStartIndex))
				{
					req.setAttribute(ConstantHelper.BLOGGER_NAME_NEXT_INDEX, liStartIndex+1);
				}//if (this.isNextFeed(liStartIndex))
				
				req.setAttribute(ConstantHelper.BLOGGER_NAME_BLOGARR, loBlogArr);
				
				getServletContext().getRequestDispatcher(PropertiesHelper.getBlogViewerPage()).forward(req, resp);
			
				return;
			}//	if (lsPathInfo == null)
				
			String[] lsPathArr = lsPathInfo.split("/");
				
			if (lsPathArr == null)
			{
				loBlogArr =  this.getBlogList(liStartIndex);
				
				if (this.isNextFeed(liStartIndex))
				{
					req.setAttribute(ConstantHelper.BLOGGER_NAME_NEXT_INDEX, liStartIndex+1);
				}//if (this.isNextFeed(liStartIndex))
	
				
				req.setAttribute(ConstantHelper.BLOGGER_NAME_BLOGARR, loBlogArr);
				
				getServletContext().getRequestDispatcher(PropertiesHelper.getBlogViewerPage()).forward(req, resp);
			
				return;
				
			}//if (lsPathArr == null)
			
			String lsMethod = lsPathArr[1];
			String lsPageNumber = lsPathArr[2];
			int liPageNumber = Integer.parseInt(lsPageNumber);
			
			if ( ConstantHelper.KEYWORD_PAGE.equalsIgnoreCase(lsMethod) && liPageNumber>1)
			{
				liStartIndex = ((liPageNumber-1) * PropertiesHelper.getBlogPageSize())+1; 
			}
							
			loBlogArr =  this.getBlogList(liStartIndex);
		
			if (this.isNextFeed(liPageNumber* PropertiesHelper.getBlogPageSize()))
			{
				req.setAttribute(ConstantHelper.BLOGGER_NAME_NEXT_INDEX, liPageNumber+1);
			}//if (this.isNextFeed(liStartIndex))

			if (liPageNumber > 1)
			{
				req.setAttribute(ConstantHelper.BLOGGER_NAME_PREVIOUS_INDEX, liPageNumber-1);
			}//	if (liPageNumber > 1)
			
			req.setAttribute(ConstantHelper.BLOGGER_NAME_BLOGARR, loBlogArr);
			
			getServletContext().getRequestDispatcher(PropertiesHelper.getBlogViewerPage()).forward(req, resp);
		
			return;
		
			
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}//doPost
	
	private boolean isNextFeed(int aiStartIndex) throws IOException, ServiceException
	{
		  final URL feedUrl = new URL(PropertiesHelper.getBlogFeedUrl());
		  Query nextyQuery = new Query(feedUrl);
		  nextyQuery.setMaxResults(1);
		  nextyQuery.setStartIndex(aiStartIndex+1);
		  Feed loNextResultFeed = myService.query(nextyQuery, Feed.class);

		  int liNextFeedSize = loNextResultFeed.getEntries().size();
		  boolean lbNextFeedFlag = (liNextFeedSize > 0)?true:false;

		  return lbNextFeedFlag;
		  
	}//isNextFeed
	
	
	private  Blog[] getBlogList(int aiStartIndex) throws IOException, ServiceException
	{
	//	GoogleService myService = new GoogleService(ConstantHelper.SERVICE_NAME_BLOGGER, ConstantHelper.APPLICATION_NAME_BLOGGER);
	//	myService.setUserCredentials(PropertiesHelper.getBlogUser(), PropertiesHelper.getBlogPwd());
		
		
		// Request the last 5 feed
		  final URL feedUrl = new URL(PropertiesHelper.getBlogFeedUrl());
		  Query myQuery = new Query(feedUrl);
		  myQuery.setMaxResults(PropertiesHelper.getBlogPageSize());
		  myQuery.setStartIndex(aiStartIndex);
		  Feed resultFeed = myService.query(myQuery, Feed.class);


		  List<Entry> loEntryList = resultFeed.getEntries();
		  
		  int liBlogSize = loEntryList.size();
		  
		  if (liBlogSize == 0)
		  {
			 //jump jump jump 
			  return null;
		  }//liBlogSize
		  
		  Blog[] loBlogArr = new Blog[liBlogSize];
		  int i = 0;
		  
		  for (Entry e:loEntryList)
		  {
			  Blog loBlog = new Blog();
			  String lsEntityId = e.getId();
			  String lsPostID = lsEntityId.substring(lsEntityId.indexOf(ConstantHelper.GDATA_API_POSTID)+ConstantHelper.GDATA_API_POSTID.length());
			  loBlog.setBlogTitle(e.getTitle().getPlainText());
			 // loBlog.setPublishDate(e.getPublished());
			  //loBlog.setBlogContent( ((TextContent) e.getContent()).getContent().getPlainText());
			  TextConstruct loBlogText = ((TextContent) e.getContent()).getContent();
			  String lsBlogHtml = ((HtmlTextConstruct)loBlogText).getHtml();
			  String lsBlogText = loBlogText.getPlainText();
			  if (lsBlogText.length() > PropertiesHelper.getBlogPreviewSize())
			  {	 
				  lsBlogText = lsBlogText.substring(0, PropertiesHelper.getBlogPreviewSize()) + "...";
			  }//if (lsBlogText.length() > PropertiesHelper.getBlogPreviewSize())	  
			  loBlog.setBlogContent(lsBlogHtml);
			  loBlog.setBlogSummary(lsBlogText);		
			  loBlog.setPostId(lsPostID);
			  loBlog.setPublishDateStr(UtilHelper.getStrDate(e.getPublished(), ConstantHelper.DATEFORMAT_FULL_DATE));
			  loBlogArr[i] = loBlog;
			  ++i;
		  }//for E
		  
		  return loBlogArr;
			  
	}//getBlogList
}//HkugBloggerServlet
